#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>

#define BOLD_GRAY "\033[1;90m"
#define RED "\033[0;31m"
#define WHITE "\033[0;37m"
#define RESET "\033[0m"

// Размер буфера для чтения
#define BUFFER_SIZE 4096

int module_05_run(const char *filename) {
    char log_msg[1024];

    FILE *file = fopen(filename, "rb");
    if (!file) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "File type not recognized: %s" RESET, strerror(errno));
        printf("%s\n", log_msg);
        return 1;
    }

    unsigned char *buffer = malloc(BUFFER_SIZE);
    if (!buffer) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Memory allocation failed" RESET);
        printf("%s\n", log_msg);
        fclose(file);
        return 1;
    }

    size_t read_bytes = fread(buffer, 1, BUFFER_SIZE, file);
    fclose(file);

    if (read_bytes == 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "File type not recognized: Empty file" RESET);
        printf("%s\n", log_msg);
        free(buffer);
        return 1;
    }

    iconv_t cd = iconv_open("UTF-8", "UTF-8");
    if (cd == (iconv_t)-1) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Error initializing iconv" RESET);
        printf("%s\n", log_msg);
        free(buffer);
        return 1;
    }

    char *inbuf = (char *)buffer;
    size_t inbytesleft = read_bytes;
    char *outbuf = malloc(BUFFER_SIZE);
    if (!outbuf) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Memory allocation failed" RESET);
        printf("%s\n", log_msg);
        iconv_close(cd);
        free(buffer);
        return 1;
    }
    char *outptr = outbuf;
    size_t outbytesleft = BUFFER_SIZE;

    size_t result = iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft);
    if (result == (size_t)-1) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " WHITE "Not UTF-8, possible binary or other encoding" RESET);
    } else {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " WHITE "Compatible with UTF-8" RESET);
    }
    printf("%s\n", log_msg);
    iconv_close(cd);
    free(outbuf);
    free(buffer);
    return 0;
}
